package com.dhc.service.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.dhc.service.annotation.Authorization;
import com.dhc.service.service.AdminInfoService;
import com.dhc.service.utils.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 认证请求头中的token的拦截器类
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

	@Autowired
	private AdminInfoService adminInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request,
	                         HttpServletResponse response,
	                         Object handler) {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;  // true表示继续流程
		}

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		Boolean existUser = false;
		boolean checkToken = false;

		//检查是否有需要用户权限的注解
		if (method.isAnnotationPresent(Authorization.class)) {
			Authorization auth = method.getAnnotation(Authorization.class);
			if (auth.required()) {
				// 从 http 请求头中取出 token
				String token = request.getHeader("Authorization");
				if (token == null) {
					throw new TokenExpiredException("无token，请重新登录");
				}
				// 获取 token 中的 user id , user name, 验证user是否存在
				try {
					String userId = JWT.decode(token).getClaim("userId").asString();
					String userName = JWT.decode(token).getAudience().get(0);
					existUser = adminInfoService.isExistByIdAndName(userId, userName);
				} catch (JWTDecodeException j) {
					throw new TokenExpiredException("402 用户不存在");
				}
				// 验证 token ， token 是否过期
				checkToken = JwtUtils.checkToken(token);
			}
		}
		return existUser && checkToken;
	}

	@Override
	public void postHandle(HttpServletRequest request,
	                       HttpServletResponse response,
	                       Object handler, ModelAndView modelAndView) {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
	                            HttpServletResponse response,
	                            Object handler, Exception ex) {
	}
}
